package com.skywolf.chem.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.exception.BizException;
import com.skywolf.chem.common.sysconfig.utils.TLBeanUtils;
import com.skywolf.chem.usercenter.entity.Permission;
import com.skywolf.chem.usercenter.entity.RolePermission;
import com.skywolf.chem.usercenter.mapper.RolePermissionMapper;
import com.skywolf.chem.usercenter.pojo.param.RolePermissionParam;
import com.skywolf.chem.usercenter.pojo.vo.PermissionVO;
import com.skywolf.chem.usercenter.service.IRolePermissionService;
import com.skywolf.chem.usercenter.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色和权限关系表 服务实现类
 * </p>
 *
 * @author
 * @since 2019-12-02
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public void saveRolePermission(RolePermissionParam rolePermissionParam) {
        Long roleId = rolePermissionParam.getRoleId();
        //查看角色是否存在
        if (!roleService.hasRole(roleId)) {
            throw new BizException(ResponseCodeEnum.ROLE_NOT_FOUND);
        }

        //删除存在的角色权限
        UpdateWrapper<RolePermission> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("role_id", roleId);
        this.remove(updateWrapper);

        //保存角色权限
        if (!CollectionUtils.isEmpty(rolePermissionParam.getPermissionIdList())) {
            List<RolePermission> rolePermissionList = new ArrayList<>();
            rolePermissionParam.getPermissionIdList().forEach(permissionId -> rolePermissionList.add(new RolePermission(roleId, permissionId)));
            this.saveBatch(rolePermissionList);
        }
    }

    @Override
    public List<PermissionVO> listRolePermission(String roleId) {
        List<Permission> permissionList = rolePermissionMapper.selectByRoleId(roleId);
        return TLBeanUtils.copyList(permissionList, PermissionVO.class);
    }

}
